package com.example.softwareconfigurationcoursedesign;

import jakarta.servlet.ServletContext;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;

@WebServlet(name = "MessageLogin", value = "/MessageLogin")

public class MessageLogin extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String code = request.getParameter("VerificationCode");
        String R_code = request.getParameter("generatedCode");
        response.setContentType("text/html;charset=utf-8");
        String phoneNum = request.getParameter("phoneNumber3");
        ServletContext context = this.getServletContext();
        String dbUrl = context.getInitParameter("DatabaseUrl");
        String dbUsername = context.getInitParameter("DatabaseUsername");
        String dbPassword = context.getInitParameter("DatabasePassword");
        String jdbcDriver = context.getInitParameter("jdbcDriver");
        System.err.println(phoneNum);
        System.err.println(R_code);
        try (Connection connection = DatabaseUtil.getCon(jdbcDriver, dbUrl, dbUsername, dbPassword); PreparedStatement pst = connection.prepareStatement("select * from users where phone_number=?")) {
            pst.setString(1, phoneNum);
            try (ResultSet rs = pst.executeQuery()) {
                if (rs.next()) {
                    if (R_code.equals(code)) {
                        response.sendRedirect("TransitionInterface.html");
                    } else {
                        PrintWriter out = response.getWriter();
                        out.println("<script>alert('登录失败 将返回主页面  请您再次尝试进行登录'); window.location.href='index.jsp';</script>");
                        out.flush();
                    }
                } else {
                    PrintWriter out = response.getWriter();
                    out.println("<script>alert('登录失败 将返回主页面 未找到该用户 请您注册之后再次尝试进行登录'); window.location.href='index.jsp';</script>");
                    out.flush();
                }
            }
        } catch (SQLException | IOException throwable) {
            Logger.getLogger(Servlet.class.getName()).log(Level.SEVERE, "数据库操作失败", throwable);
            response.sendRedirect("error.html");
        }
    }
}

